package com.engineering.elink.xaservice.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.engineering.elink.co.CourseAddCo;
import com.engineering.elink.co.recruit.JobAddCo;
import com.engineering.elink.common.DictConstant;
import com.engineering.elink.domain.Chapter;
import com.engineering.elink.domain.ChapterVideo;
import com.engineering.elink.domain.Course;
import com.engineering.elink.domain.Evaluate;
import com.engineering.elink.domain.Label;
import com.engineering.elink.domain.Video;
import com.engineering.elink.domain.VideoComment;
import com.engineering.elink.domain.VideoSubtitle;
import com.engineering.elink.domain.hier.HierTitle;
import com.engineering.elink.domain.recruit.CvDatabase;
import com.engineering.elink.domain.recruit.DictCategory;
import com.engineering.elink.domain.recruit.Job;
import com.engineering.elink.domain.recruit.JobFunctions;
import com.engineering.elink.domain.recruit.JobLanguage;
import com.engineering.elink.domain.recruit.JobProfessional;
import com.engineering.elink.domain.recruit.VitaCollection;
import com.engineering.elink.domain.recruit.VitaCollectionBak;
import com.engineering.elink.domain.recruit.VitaDelivery;
import com.engineering.elink.domain.recruit.VitaDeliveryBak;
import com.engineering.elink.domain.skill.Skill;
import com.engineering.elink.hessian.AliyunHessianService;
import com.engineering.elink.hierdao.HierTitleMapper;
import com.engineering.elink.recruitdao.CvDatabaseMapper;
import com.engineering.elink.recruitdao.DictCategoryMapper;
import com.engineering.elink.recruitdao.JobFunctionsMapper;
import com.engineering.elink.recruitdao.JobLanguageMapper;
import com.engineering.elink.recruitdao.JobMapper;
import com.engineering.elink.recruitdao.JobProfessionalMapper;
import com.engineering.elink.recruitdao.VitaCollectionBakMapper;
import com.engineering.elink.recruitdao.VitaCollectionMapper;
import com.engineering.elink.recruitdao.VitaDeliveryBakMapper;
import com.engineering.elink.recruitdao.VitaDeliveryMapper;
import com.engineering.elink.skilldao.SkillMapper;
import com.engineering.elink.videodao.ChapterMapper;
import com.engineering.elink.videodao.ChapterVideoMapper;
import com.engineering.elink.videodao.CourseMapper;
import com.engineering.elink.videodao.EnrollMapper;
import com.engineering.elink.videodao.EvaluateMapper;
import com.engineering.elink.videodao.LabelMapper;
import com.engineering.elink.videodao.VideoCommentMapper;
import com.engineering.elink.videodao.VideoMapper;
import com.engineering.elink.videodao.VideoSubtitleMapper;
import com.engineering.elink.vo.ChapterVo;
import com.engineering.elink.vo.EvaluateAddVo;
import com.engineering.elink.vo.VideoVo;
import com.engineering.elink.xaservice.EvaluateXaService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.zxy.core.enums.ErrorType;
import com.zxy.core.util.CollectionUtil;
import com.zxy.core.util.DateUtil;
import com.zxy.core.util.JsonBinderUtil;
import com.zxy.core.util.ResJsonUtil;
import com.zxy.core.util.TimeToolUtil;
import com.zxy.core.util.UUIDUtil;

/**
 * 评价方面业务事务操作实现类
 * 
 * ClassName: EvaluateXaServiceImpl <br/> 
 * Function: ADD FUNCTION. <br/> 
 * Reason: ADD REASON(可选). <br/> 
 * date: 2016年11月10日 上午10:50:25 <br/> 
 * 
 * @author zengxinyan 
 * @version  
 * @since JDK 1.8
 */
@Service
public class EvaluateXaServiceImpl implements EvaluateXaService{
	
	private static Logger logger = Logger.getLogger(EvaluateXaServiceImpl.class);

	@Autowired
	private EvaluateMapper evaluateMapper;
	
	@Autowired
	private CourseMapper courseMapper;
	
	@Autowired
	private EnrollMapper enrollMapper;
	
	@Autowired
	private SkillMapper skillMapper;
	
	
	@Autowired
	private VideoCommentMapper videoCommentMapper;
	
	@Autowired
	private VideoMapper videoMapper;
	
	@Autowired
	private LabelMapper labelMapper;
	
	@Autowired
	private HierTitleMapper htMapper;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private ChapterMapper chapterMapper;
	
	@Autowired
	private ChapterVideoMapper chapterVideoMapper;
	
	@Autowired
	private JobFunctionsMapper jobFunctionsMapper;
	
	@Autowired
	private JobLanguageMapper jobLanguageMapper;
	
	@Autowired
	private JobProfessionalMapper jobProfessionalMapper;
	
	@Autowired
	private JobMapper jobMapper;
	
	@Autowired
	private VitaDeliveryBakMapper vitaDeliveryBakMapper;
	
	@Autowired
	private VitaDeliveryMapper vitaDeliveryMapper;
	
	@Autowired
	private CvDatabaseMapper cvDatabaseMapper;
	

	@Autowired
	private VitaCollectionBakMapper vitaCollectionBakMapper;
	
	@Autowired
	private VitaCollectionMapper vitaCollectionMapper;
	
	@Autowired
	private AliyunHessianService aliyunHessianService;
	
	@Autowired
	private VideoSubtitleMapper videoSubtitleMapper;
	
	@Autowired
	private DictCategoryMapper dictCategoryMapper;
	
	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.EvaluateService#add(java.lang.Integer, java.lang.String, java.lang.String, java.lang.Integer)
	 */
	@Override
	public Map<String, Object> add(EvaluateAddVo vo) {
		
		if(vo.getType()==0){
			//课程评价
			return addCourse(vo);
		}else if(vo.getType()==1){
			//技能评价
			return addSkill(vo);
		}
		
		return ResJsonUtil.getMap(ErrorType.REQUEST_PARAMS_ERROR);
	}
	
	private Map<String,Object> addCourse(EvaluateAddVo vo){
		Course course = courseMapper.selectByPrimaryKey(vo.getId());
		if(course != null){
			vo.setByUserId(course.getCreateUserId());
			
			//当课程收费时，只有购买了以后，才能评价，免费时可以评价；
			if(course.getPrice()==null || course.getPrice().floatValue()<=0){
				
				if(saveEvaluate(vo)){
					return ResJsonUtil.getMap(ErrorType.COURSE_EVALCOUNT_ERROR);
				}
			}else{
				//收费
				int count=enrollMapper.selectCountEnroll(vo.getId(),vo.getUserId());
				if(count>0){
					if(saveEvaluate(vo)){
						return ResJsonUtil.getMap(ErrorType.COURSE_EVALCOUNT_ERROR);
					}
				}else{
					return ResJsonUtil.getMap(ErrorType.COURSE_ENROLL_ERROR);
				}
			}
		
			//更新课程的评价数量
			course.setCommentCount(course.getCommentCount()+1);
			courseMapper.updateByPrimaryKeySelective(course);
			
			return ResJsonUtil.getMap(ErrorType.SUCCESS);
		}
		
		return ResJsonUtil.getMap(ErrorType.COURSE_EVALUATE_ERROR);
	}
	
	private Map<String,Object> addSkill(EvaluateAddVo vo){
		Skill skill = skillMapper.selectByPrimaryKey(vo.getId());
		if(skill != null){
			vo.setByUserId(skill.getCreateUserId());
			
			if(saveEvaluate(vo)){
				return ResJsonUtil.getMap(ErrorType.SKILL_EVALCOUNT_ERROR);
			}
		
			//更新技能的评价数量
			skill.setCommentCount(skill.getCommentCount()+1);
			skillMapper.updateByPrimaryKeySelective(skill);
			
			return ResJsonUtil.getMap(ErrorType.SUCCESS);
		}
		
		return ResJsonUtil.getMap(ErrorType.SKILL_EVALCOUNT_ERROR);
	}
	

	/**
	 * 保存评价
	 * 
	 * saveEvaluate:(这里用一句话描述这个方法的作用). <br/> 
	 * (这里描述这个方法适用条件 – 可选).<br/> 
	 * (这里描述这个方法的执行流程 – 可选).<br/> 
	 * (这里描述这个方法的使用方法 – 可选).<br/> 
	 * (这里描述这个方法的注意事项 – 可选).<br/> 
	 * 
	 * @author zengxinyan 
	 * @param course
	 * @param content
	 * @param userId
	 * @param evalCount 
	 * @since JDK 1.8
	 */
	private boolean saveEvaluate(EvaluateAddVo vo){
		//针对评价只允许一次
		int count=evaluateMapper.selectCountEvaluate(vo.getId(),vo.getUserId(),vo.getType());
		if(count>0){
			return true;
		}
		
		Evaluate c = new Evaluate();
		c.setCourseId(vo.getId());
		c.setContent(vo.getContent());
		c.setTime(new Date());
		c.setPraiseCount(0);
		c.setStampCount(0);
		c.setUserId(vo.getUserId());
		c.setByUserId(vo.getByUserId());
		c.setParentId(0);//顶级评论的父类id为0
		c.setEvalCount(vo.getEvalCount());
		c.setTopId(0);//只评价一次，层级给0
		c.setType(vo.getType());
		
		evaluateMapper.insertSelective(c);
		
		return false;
	}
	
	
	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.EvaluateService#addReplyEvaluate(java.lang.Integer, java.lang.Integer, java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String, Object> addReplyEvaluate(Integer courseId,Integer evaluateId, String userId,String content,int type) {
		Evaluate c = evaluateMapper.selectByPrimaryKey(evaluateId);
		
		if(c != null){
			Evaluate c1 = new Evaluate();
			c1.setCourseId(courseId);
			c1.setContent(content);
			c1.setTime(new Date());
			c1.setPraiseCount(0);
			c1.setStampCount(0);
			c1.setUserId(userId);
			c1.setByUserId(c.getUserId());
			
			c1.setParentId(c.getEvaluateId());//父类id为被评价的评价id
			/**
			 * 根据被评价的评价ID去取层级ID，也就是最顶层的评价ID
			 */
			c1.setTopId(evaluateMapper.selectTopByRootId(c.getEvaluateId()));
			
			c1.setType(type);
			
			if(type==0){
				//更新课程的评价数量
				Course course= courseMapper.selectByPrimaryKey(courseId);
				course.setCommentCount(course.getCommentCount()+1);
				courseMapper.updateByPrimaryKeySelective(course);
			}else if(type==1){
				//更新技能的评价数量
				Skill skill= skillMapper.selectByPrimaryKey(courseId);
				skill.setCommentCount(skill.getCommentCount()+1);
				skillMapper.updateByPrimaryKeySelective(skill);
			}else{
				return ResJsonUtil.getMap(ErrorType.EVALUATE_REPLY_ERROR);
			}
			
			evaluateMapper.insertSelective(c1);
			
			return ResJsonUtil.getMap(ErrorType.SUCCESS);
		}else{
			return ResJsonUtil.getMap(ErrorType.EVALUATE_REPLY_ERROR);
		}
		
	}
	
	
	
	@Override
	public Map<String, Object> addVideo(Integer videoId,String userId, String content) {
		Video video = videoMapper.selectByPrimaryKey(videoId);
		if(video != null){
			
			if(saveComment(video,content,userId)){
				return ResJsonUtil.getMap(ErrorType.VIDEO_COMMENTCOUNT_ERROR);
			}
			
			//更新视频的评论数量
			video.setCommentCount(video.getCommentCount()+1);
			videoMapper.updateByPrimaryKeySelective(video);
			
			//更新课程的评论数量
			//List<Integer> cIdList=chapterMapper.selectCourseId(videoId);
			
			List<Course> courseList=courseMapper.selectCourseByVideoId(videoId);
			for(Course course:courseList){
				if(course!=null){
					course.setCommentCount(course.getCommentCount()+1);
					courseMapper.updateByPrimaryKeySelective(course);
				}
				
			}
			
			//更新工程技能评价数量
			List<Skill> skillList=skillMapper.selectSkillByVideoId(videoId);
			for(Skill skill:skillList){
				if(skill!=null){
					skill.setCommentCount(skill.getCommentCount()+1);
					skillMapper.updateByPrimaryKeySelective(skill);
				}
			}
			
			return ResJsonUtil.getMap(ErrorType.SUCCESS);	
			//return JSONUtil.getMap(ErrorType.COURSE_EVALUATE_ERROR);
			
		}
		
		return ResJsonUtil.getMap(ErrorType.FILE_COMMENT_ERROR);

	}
	
	private boolean saveComment(Video video,String content,String userId){
		//针对视频评论只允许一次
		int count=videoCommentMapper.selectCountComment(video.getVideoId(),userId);
		if(count>0){
			return true;
		}
		
		VideoComment c = new VideoComment();
		c.setVideoId(video.getVideoId());
		c.setContent(content);
		c.setTime(new Date());
		c.setPraiseCount(0);
		c.setStampCount(0);
		c.setUserId(userId);
		c.setByUserId(video.getUploadUserid());
		c.setParentId(0);//顶级评论的父类id为0
		c.setTopId(0);//只评价一次，层级给0
		
		videoCommentMapper.insertSelective(c);
		
		return false;
	}
	
	
	@Override
	public Map<String, Object> addReply(Integer videoId,Integer commentId, String userId,String content) {
		VideoComment c = videoCommentMapper.selectByPrimaryKey(commentId);
		if(c != null){
			VideoComment c1 = new VideoComment();
			c1.setVideoId(videoId);
			c1.setContent(content);
			c1.setTime(new Date());
			c1.setPraiseCount(0);
			c1.setStampCount(0);
			c1.setUserId(userId);
			c1.setByUserId(c.getUserId());
			
			c1.setParentId(c.getCommentId());//父类id为被评价的评价id
			/**
			 * 根据被评价的评价ID去取层级ID，也就是最顶层的评价ID
			 */
			c1.setTopId(videoCommentMapper.selectTopByRootId(c.getCommentId()));
			
			//更新视频的评论数量
			Video video= videoMapper.selectByPrimaryKey(videoId);
			video.setCommentCount(video.getCommentCount()+1);
			videoMapper.updateByPrimaryKeySelective(video);
			
			videoCommentMapper.insertSelective(c1);
			
			//更新课程的评论数量
			List<Course> courseList=courseMapper.selectCourseByVideoId(videoId);
			for(Course course:courseList){
				if(course!=null){
					course.setCommentCount(course.getCommentCount()+1);
					courseMapper.updateByPrimaryKeySelective(course);
				}
				
			}
			
			//更新工程技能评价数量
			List<Skill> skillList=skillMapper.selectSkillByVideoId(videoId);
			for(Skill skill:skillList){
				if(skill!=null){
					skill.setCommentCount(skill.getCommentCount()+1);
					skillMapper.updateByPrimaryKeySelective(skill);
				}
			}
			
			//return JSONUtil.getMap(ErrorType.COURSE_EVALUATE_ERROR);
	
			return ResJsonUtil.getMap(ErrorType.SUCCESS);
			
		}else{
			return ResJsonUtil.getMap(ErrorType.COMMENT_REPLY_ERROR);
		}
		
	}

	@Override
	public void insertHierTitleMapper(HierTitle ht) {
		this.htMapper.insertSelective(ht);
	}

	@Override
	public void insertVideoLabel(Label label) {
		this.labelMapper.insertSelective(label);
	}
	
	@Override
    public void saveHierTitle(String name) {
    	
        String sql = "insert into hier_title (name) values ('" + name + "')";
        
        jdbcTemplate.update(sql);
    }

	@Override
	public Integer saveCourse(CourseAddCo addCo, String userId) throws Exception{
		Course course=new Course();
		
		PropertyUtils.copyProperties(course, addCo);
		
		course.setSize(0);
		course.setDownloadCount(0);
		course.setCollectionCount(0);
		course.setCommentCount(0);
		course.setAuthStatus(0);
		course.setDeleteStatus(0);
		course.setCreateTime(new Date()); 
		course.setPublishStatus(0);
		course.setCreateUserId(userId);
		course.setVisitCount(0);
		
		//更新标签
		course.setLabelIds(updateLabel(course.getLabelIds(),userId));
		
		//插入课程
		courseMapper.insertSelective(course);
		
		if(StringUtils.isNotEmpty(addCo.getJsonStr())){
			//保存章节
			saveChapter(course.getCourseId(),addCo.getJsonStr(),userId);
		}
		
		return course.getCourseId();
	
	}
	
	private void saveChapter(Integer courseId,String jsonStr,String userId){
		List<ChapterVo> parentList=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<ChapterVo>>(){});
		
		Chapter parentChapter=null;
		Chapter childChapter=null;
		ChapterVideo chapterVideo=null;
		Video oldVideo=null;
		int count=0;
		
		Course c=courseMapper.selectByPrimaryKey(courseId);
		if(c==null){
			throw new RuntimeException("课程信息不存在！");
		}
		int size=c.getSize();
		
		for(ChapterVo pvo:parentList){
			if(pvo==null)continue;
			//新增章
			if(pvo!=null && pvo.getChapterId().intValue()==0){
				parentChapter=new Chapter(pvo.getChapterName(),0,courseId,chapterMapper.getMaxSortId(0, courseId)+1);
				chapterMapper.insertSelective(parentChapter);
			}else{
				//修改
				parentChapter=new Chapter(pvo.getChapterId(),pvo.getChapterName());
				chapterMapper.updateByPrimaryKeySelective(parentChapter);
			}
			
			List<VideoVo> childList=pvo.getChildChapterList();
			for(VideoVo vo:childList){
				if(vo==null)continue;
				//新增节
				if(vo!=null && vo.getChapterId().intValue()==0){
					childChapter=new Chapter(vo.getChapterName(),parentChapter.getChapterId(),courseId,chapterMapper.getMaxSortId(parentChapter.getChapterId(), courseId)+1);
					chapterMapper.insertSelective(childChapter);
				}else{
					//修改
					childChapter=new Chapter(vo.getChapterId(),vo.getChapterName());
					chapterMapper.updateByPrimaryKeySelective(childChapter);
				}
				
				List<Video> videoList=vo.getVideoList();
				//
				List<Integer> cvList=chapterVideoMapper.selectByChapterId(childChapter.getChapterId());
				
				for(Video video:videoList){
					if(video==null)continue;
					
					//新增
					if(video!=null && video.getVideoId().intValue()==0){
						video.setVideoId(null);
						
						//写入video表
						video.setUploadUserid(userId);
						video.setUploadTime(DateUtil.getDate());
						video.setType(0);
						video.setTrancodeStatus(0);
						//待审核
						video.setStatus(0);
						
						videoMapper.insertSelective(video);
					
					}
					else{
						oldVideo=videoMapper.selectByPrimaryKey(video.getVideoId());
						if(oldVideo==null){
							throw new RuntimeException(ErrorType.VIDEO_ERROR.getMsg());
						}
						
						oldVideo.setVideoName(video.getVideoName());
						
						videoMapper.updateByPrimaryKeySelective(oldVideo);
						
					}
					
					//判断重复
					count=this.chapterVideoMapper.countChapterVideo(video.getVideoId(),childChapter.getChapterId());
					if(count>0){
						throw new RuntimeException("其他课程的章节下面已存在此视频，视频名称为["+video.getVideoName()+"],请您对其进行修改！");
					}
					
					ChapterVideo cv=chapterVideoMapper.selectChapterVideo(video.getVideoId(),childChapter.getChapterId());
					if(cv!=null){
						cvList.remove(cv.getCvId());
					}else{
						//插入节与视频的关联表
						chapterVideo=new ChapterVideo(childChapter.getChapterId(),video.getVideoId(),chapterVideoMapper.getChapterSortId(childChapter.getChapterId())+1);
						chapterVideoMapper.insertSelective(chapterVideo);
						size++;
					}
					
				}
				//删除
				if(CollectionUtil.collectionIsNotEmpty(cvList)){
					size=size-cvList.size();
					chapterVideoMapper.deleteBatchByCvId(cvList);
				}
				
			}
		}
		
		//更新课程视频个数
		c.setSize(size);
		courseMapper.updateByPrimaryKeySelective(c);
		
	}
	
	private String updateLabel(String labels,String userId){
		//对标签 做处理，先插再取ID值
		if(StringUtils.isNotEmpty(labels)){
			String[] labelArray=StringUtils.split(labels, ',');
			StringBuilder sb=new StringBuilder();
			Label lb=null;
			int id=0;
			List<Label> list=null;
			for(String labelName:labelArray){
				list=labelMapper.selectByLabelNameType(labelName, 0);
				if(CollectionUtil.collectionIsNotEmpty(list)){
					lb=list.get(0);
				}
				if(lb==null){
					lb=new Label(labelName,userId,0);
					//id返回的是插入行数
					id=labelMapper.insertSelective(lb);
				}else{
					lb.setUserId(userId);
					id=labelMapper.updateByPrimaryKeySelective(lb);
				}
				
				logger.info("发布课程时插入标签,返回插入行数为："+id); 
				//通过selectKey的SELECT LAST_INSERT_ID() AS labelId这种方式会把ID值给到入参对象中
				sb.append(lb.getLabelId()+",");
			}
			//重新设置标签值
			return sb.toString();
		}
		return null;
	}

	@Override
	public void updateCourse(Course course, CourseAddCo addCo, String userId) throws Exception {
		
		PropertyUtils.copyProperties(course, addCo);
		
		course.setUpdateTime(new Date());
		course.setUpdateUserId(userId);
		
		//更新标签
		course.setLabelIds(updateLabel(course.getLabelIds(),userId));
		
		//更新课程
		courseMapper.updateByPrimaryKeySelective(course);
		
		if(StringUtils.isNotEmpty(addCo.getJsonStr())){
			//保存章节
			saveChapter(course.getCourseId(),addCo.getJsonStr(),userId);
		}
	}

	@Override
	public String saveJob(JobAddCo addCo, String userId) throws Exception {
		Job job=new Job();
		
		PropertyUtils.copyProperties(job, addCo);
		
		//生成jobId
		String jobId=UUIDUtil.getUUID();
		job.setJobId(jobId);
		job.setCloseStatus(0);
		job.setCreateTime(new Date());
		job.setCreateUserId(userId);
		job.setDeleteStatus(0);
		job.setCompanyId(userId);
		
		if(job.getType()!=null && job.getType()==1){
			//实习
			DictCategory dc=dictCategoryMapper.selectByNatureId(job.getNatureId());
			DictCategory dd=null;
			if(dc!=null && dc.getDictName().contains("全职")){
				dd=dictCategoryMapper.selectBySequence(DictConstant.JOB_NATURE, DictCategory.NATURE_SEQ_ONE);
			}else if(dc!=null && dc.getDictName().contains("兼职")){
				dd=dictCategoryMapper.selectBySequence(DictConstant.JOB_NATURE, DictCategory.NATURE_SEQ_ZERO);
			}
			if(dd!=null){
				job.setNatureId(dd.getDictId());
			}
		}
		
		//插入职位
		jobMapper.insertSelective(job);
		
		//职能
		String[] fdetails=StringUtils.split(addCo.getFunctionsDetailIds(),',');
		if(CollectionUtil.arrayIsNotEmpty(fdetails)){
			List<JobFunctions> jfList=new ArrayList<JobFunctions>();
			for(String fd:fdetails){
				if(StringUtils.isEmpty(fd))continue;
				jfList.add(new JobFunctions(jobId,Integer.valueOf(fd)));
			}
			//批量插入
			if(CollectionUtil.collectionIsNotEmpty(jfList)){
				logger.info("批量插入职位职能中间表影响行数为："+jobFunctionsMapper.insertBatch(jfList));
				
			}
		}
		
		//语言
		if(StringUtils.isNotEmpty(addCo.getLanguageJsonStr())){
			List<JobLanguage> jlList=JsonBinderUtil.fromJsontolist(addCo.getLanguageJsonStr(),new TypeReference<List<JobLanguage>>(){});
			if(CollectionUtil.collectionIsNotEmpty(jlList)){
				for(JobLanguage jl:jlList){
					if(jl!=null){
						jl.setJlId(null);
						jl.setJobId(jobId);
					}
				}
				//批量插入
				logger.info("批量插入职位语言中间表影响行数为："+jobLanguageMapper.insertBatch(jlList));
			}
		}
		
		//专业
		if(StringUtils.isNotEmpty(addCo.getProfeJsonStr())){
			List<JobProfessional> jpList=JsonBinderUtil.fromJsontolist(addCo.getProfeJsonStr(),new TypeReference<List<JobProfessional>>(){});
			if(CollectionUtil.collectionIsNotEmpty(jpList)){
				for(JobProfessional jp:jpList){
					if(jp!=null){
						jp.setJpId(null);
						jp.setJobId(jobId);
					}
				}
				//批量插入
				logger.info("批量插入职业专业中间表所影响的行数为："+jobProfessionalMapper.insertBatch(jpList));
			}
		}
		
		return jobId;
		
	}
	
	@Override
	public void updateJob(Job job, JobAddCo addCo, String userId) throws Exception {
		PropertyUtils.copyProperties(job, addCo);
		
		job.setUpdateTime(new Date());
		job.setUpdateUserId(userId);
		
		if(job.getType()!=null && job.getType()==1){
			//实习
			DictCategory dc=dictCategoryMapper.selectByNatureId(job.getNatureId());
			DictCategory dd=null;
			if(dc!=null && dc.getDictName().contains("全职")){
				dd=dictCategoryMapper.selectBySequence(DictConstant.JOB_NATURE, DictCategory.NATURE_SEQ_ONE);
			}else if(dc!=null && dc.getDictName().contains("兼职")){
				dd=dictCategoryMapper.selectBySequence(DictConstant.JOB_NATURE, DictCategory.NATURE_SEQ_ZERO);
			}
			if(dd!=null){
				job.setNatureId(dd.getDictId());
			}
		}
		
		//修改职位
		jobMapper.updateByPrimaryKeySelective(job);
		
		//职能
		String[] fdetails=StringUtils.split(addCo.getFunctionsDetailIds(),',');
		if(CollectionUtil.arrayIsNotEmpty(fdetails)){
			
			JobFunctions jf=null;
			for(String fd:fdetails){
				if(StringUtils.isEmpty(fd))continue;
				jf=jobFunctionsMapper.selectInfoBy(job.getJobId(), Integer.valueOf(fd));
				if(jf==null){
					jobFunctionsMapper.insertSelective(new JobFunctions(job.getJobId(),Integer.valueOf(fd)));
				}
				
			}
			//批量删除
			logger.info("批量删除职能所影响的行数为："+jobFunctionsMapper.deleteBatch(job.getJobId(), fdetails));
		}
		
		//语言
		if(StringUtils.isNotEmpty(addCo.getLanguageJsonStr())){
			List<JobLanguage> jlList=JsonBinderUtil.fromJsontolist(addCo.getLanguageJsonStr(),new TypeReference<List<JobLanguage>>(){});
			
			if(CollectionUtil.collectionIsNotEmpty(jlList)){
				for(JobLanguage jl:jlList){
					if(jl==null)continue;
					jl.setJobId(job.getJobId());
					if(jl.getJlId()==null || jl.getJlId().intValue()==0){
						jl.setJlId(null);
						jobLanguageMapper.insertSelective(jl); 
					}else{
						jobLanguageMapper.updateByPrimaryKeySelective(jl);
					}
				}
			}
		}
		
		//专业
		if(StringUtils.isNotEmpty(addCo.getProfeJsonStr())){
			List<JobProfessional> jpList=JsonBinderUtil.fromJsontolist(addCo.getProfeJsonStr(),new TypeReference<List<JobProfessional>>(){});
			if(CollectionUtil.collectionIsNotEmpty(jpList)){
				for(JobProfessional jp:jpList){
					if(jp==null)continue;
					jp.setJobId(job.getJobId());
					if(jp.getJpId()==null || jp.getJpId().intValue()==0){
						jp.setJpId(null);
						jobProfessionalMapper.insertSelective(jp);
					}else{
						jobProfessionalMapper.updateByPrimaryKeySelective(jp); 
					}
				}
			}
		}
		
	}

	@Override
	public void deliveryJob(String jobId, String userId) throws Exception {
		Job job=jobMapper.selectByPrimaryKey(jobId);
		if(job==null || StringUtils.isEmpty(job.getJobId()) || job.getDeleteStatus()!=0){
			throw new RuntimeException(ErrorType.JOB_ERROR.getMsg());
		}
		
		CvDatabase cvd=cvDatabaseMapper.selectByUserId(userId);
		if(cvd==null || StringUtils.isEmpty(cvd.getCvdId())){
			throw new RuntimeException(ErrorType.CVDATABASE_ERROR.getMsg());
		}
		
		VitaDelivery vd=vitaDeliveryMapper.selectVdById(cvd.getCvdId(),job.getCompanyId(),5);
		if(vd!=null){
			String curStr=DateUtil.get4yMdHms(DateUtil.addDay(DateUtil.getDate(), -30));
			
			if(TimeToolUtil.compareTwoDate(DateUtil.get4yMdHms(vd.getTime()), curStr)>=0){
				throw new RuntimeException(ErrorType.DELIVERY_REPEAT_ERROR.getMsg());
			}
			//可以投递,复制数据到备份表
			
			vitaDeliveryBakMapper.insertSelective(new VitaDeliveryBak(vd.getJobId(),vd.getCvdId(),vd.getCompanyId(),vd.getType(),vd.getTime()));
			vitaDeliveryMapper.deleteByPrimaryKey(vd.getVdId());
			
			VitaCollection vc=vitaCollectionMapper.selectVcById(cvd.getCvdId(), job.getCompanyId(),4);
			if(vc!=null){
				//简历库
				vitaCollectionBakMapper.insertSelective(new VitaCollectionBak(vc.getCompanyId(),vc.getCvdId(),vc.getJobId(),vc.getStatus(),vc.getCreateTime()));
				vitaCollectionMapper.deleteByPrimaryKey(vc.getVcId());
			}
		}
		
		this.vitaDeliveryMapper.insertSelective(new VitaDelivery(jobId,cvd.getCvdId(),job.getCompanyId(),0));
	}

	@Override
	public void syncVideo(String cloudAddress, String userId, Video video,List<VideoSubtitle> vsList) {
		String ossId=aliyunHessianService.checkOssRecord(userId, cloudAddress);
		if(StringUtils.isEmpty(ossId)){
			throw new RuntimeException(ErrorType.GET_OSSID_ERROR.getMsg());
		}
		
		Video oldVideoInfo=videoMapper.selectByOssId(ossId);
		if(oldVideoInfo==null){
			
			//写入video表
			video.setUploadUserid(userId);
			video.setUploadTime(DateUtil.getDate());
			video.setType(0);
			video.setTrancodeStatus(0);
			video.setOssId(ossId);
			video.setCloudAddress(cloudAddress);
			//待审核
			video.setStatus(0);
			
			video.setVisitCount(0);
			video.setFreeStatus(0);
			video.setFreeTime(0);
			
			boolean flag=aliyunHessianService.transcodeVideo(ossId);
			if(flag){
				video.setTrancodeStatus(1);
			}
			
			this.videoMapper.insertSelective(video);
			
			VideoSubtitle vs=null;
			if(CollectionUtil.collectionIsNotEmpty(vsList)){
			for(VideoSubtitle vsub:vsList){
				if(vsub==null)continue;
				
				vs=videoSubtitleMapper.selectByVideoId(video.getVideoId(), vsub.getType());
				if(vs==null){
					vs=new VideoSubtitle();
					vs.setVideoId(video.getVideoId());
					vs.setType(vsub.getType());
					vs.setAddress(vsub.getAddress());
					videoSubtitleMapper.insertSelective(vs);
				}else{
					vs.setAddress(vsub.getAddress());
					videoSubtitleMapper.updateByPrimaryKeySelective(vs);
				}
				
			}
			}
			
		}
	
		
	}
	
}
